package com.sykj.why.mongo.service.impl;

import com.sykj.why.exception.WhyException;
import com.sykj.why.mongo.dao.AlbumTDao;
import com.sykj.why.mongo.document.entity.*;
import com.sykj.why.mongo.dto.entity.AlbumTDTO;
import com.sykj.why.mongo.enums.SolrEnum;
import com.sykj.why.mongo.enums.exception.ResultEnum;
import com.sykj.why.mongo.service.*;
import com.sykj.why.mongo.vo.entity.AlbumTVo;
import com.sykj.why.mongo.vo.entity.ContentTVo;
import com.sykj.why.mongo.vo.entity.SuccessorProjectTVo;
import com.sykj.why.thread.SolrThread;
import com.sykj.why.util.BaseTools;
import com.sykj.why.util.DateTool;
import com.sykj.why.util.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sykj.why.common.CommonConstants.HERITAGE_URL;

/**
 * @author Eleven
 * @date 2019/6/4
 * @date 专辑业务实现层
 */

@Service("AlbumTService")
public class AlbumTServiceImpl extends BaseServiceImpl<AlbumT> implements AlbumTService {

    @Autowired
    private AlbumTDao albumTDao;

    @Autowired
    private ContentTService contentTService;

    @Autowired
    private SuccessorProjectTService successorProjectTService;

    @Autowired
    private MenuCategoryTService menuCategoryTService;

    @Autowired
    private AuxiliaryCategoryTService auxiliaryCategoryTService;

    @Autowired
    private ContentCategoryTService contentCategoryTService;

    @Autowired
    private SolrService solrService;

    @Autowired
    private MenuTService menuTService;

    /**
     * 添加专辑
     * @param albumT
     */
    @Override
    public void saveAlbum(AlbumT albumT) {
        //验证专辑名称是否重复
        verifyName(albumT);
        //排序
        long count = albumTDao.count(AlbumT.class, false);
        albumT.setSort((int) count);
        //设置默认浏览次数
        albumT.setViewsNum(1);
        //设置时间
        albumT.setCreateTime(DateTool.getSystemTime());
        albumT.setUpdateTime(DateTool.getSystemTime());
        //保存
        albumTDao.save(albumT);

        ContentCategoryT contentCategoryT = contentCategoryTService.findById(albumT.getContentCategoryId());
        new SolrThread(solrService, new SolrDocumentT(
                albumT.getId(),
                SolrEnum.Document.HERITAGE.getState(),
                albumT.getAlbumName(),
                albumT.getCover(),
                albumT.getAlbumIntro(),
                contentCategoryT.getUrl()+HERITAGE_URL + albumT.getId(),
                albumT.getContentCategoryId(),
                contentCategoryT.getCategoryName(),
                true
        )).start();
    }

    /**
     * 删除专辑
     * @param id
     */
    @Override
    public void removeAlbum(String id) {
        //通过Id查询专辑
        AlbumT albumT = findById(id);
        //逻辑删除专辑
        albumTDao.remove(albumT);
        //删除专辑下的内容
        List<ContentTVo> contentTVos = contentTService.findByAlbum(id,albumT.getContentCategoryId());
        if (contentTVos!=null){
            for (ContentTVo contentTVo : contentTVos){
                contentTService.removeContent(contentTVo.getId());
            }
        }

        solrService.remove(id);
    }

    /**
     * 修改专辑
     * @param albumT
     */
    @Override
    public void updateAlbum(AlbumT albumT) {
        //通过id查询专辑
        AlbumT album = findById(albumT.getId());
        //重新赋值
        //验证专辑名称是否重复
        verifyName(albumT);
        album.setAlbumName(albumT.getAlbumName());
        album.setCover(albumT.getCover());
        album.setAuthor(albumT.getAuthor());
        album.setAlbumIntro(albumT.getAlbumIntro());
        album.setContentCategoryId(albumT.getContentCategoryId());
        album.setAuxiliaryCategoryId(albumT.getAuxiliaryCategoryId());
        album.setUpdateTime(DateTool.getSystemTime());
        //保存或修改
        albumTDao.saveOrupdate(album);

        ContentCategoryT contentCategoryT = contentCategoryTService.findById(album.getContentCategoryId());
        new SolrThread(solrService, new SolrDocumentT(
                album.getId(),
                SolrEnum.Document.HERITAGE.getState(),
                album.getAlbumName(),
                album.getCover(),
                album.getAlbumIntro(),
                contentCategoryT.getUrl()+HERITAGE_URL + album.getId(),
                album.getContentCategoryId(),
                contentCategoryT.getCategoryName(),
                true
        )).start();
    }

    /**
     * 启用/禁用专辑
     * @param id
     * @param flag
     */
    @Override
    public void disableOrEnable(String id, boolean flag) {
        //通过id查询专辑
        AlbumT albumT = findById(id);
        //修改状态
        albumTDao.disableOrEnable(albumT,flag);

        ContentCategoryT contentCategoryT = contentCategoryTService.findById(albumT.getContentCategoryId());
        new SolrThread(solrService, new SolrDocumentT(
                albumT.getId(),
                SolrEnum.Document.HERITAGE.getState(),
                albumT.getAlbumName(),
                albumT.getCover(),
                albumT.getAlbumIntro(),
                contentCategoryT.getUrl()+HERITAGE_URL + albumT.getId(),
                albumT.getContentCategoryId(),
                contentCategoryT.getCategoryName(),
                flag
        )).start();
    }

    /**
     * 验证专辑名称是否重复
     * @param albumT
     */
    @Override
    public void verifyName(AlbumT albumT) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").ne(albumT.getId()).and("albumName").is(albumT.getAlbumName()).
                and("menuCategoryId").is(albumT.getMenuCategoryId()).and("removed").is(false));
        AlbumT album = albumTDao.findOne(query,AlbumT.class);
        if (album != null) {
            throw new WhyException(ResultEnum.REPEAT);
        }
    }

    /**
     * 通过id查询专辑
     * @param id
     * @return
     */
    @Override
    public AlbumT findById(String id) {
        //通过id查询未删除的专辑
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id).and("removed").is(false));
        AlbumT albumT = albumTDao.findOne(query,AlbumT.class);
        if (albumT!=null){
            return albumT;
        }else {
            solrService.remove(id);
            throw new WhyException(ResultEnum.OBJISNULL);
        }
    }

    /**
     * 通过id查询专辑信息
     * @param id
     * @return
     */
    @Override
    public AlbumTVo findInfoById(String id) {
        //通过id查询未删除的专辑
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id).and("removed").is(false));
        AlbumT albumT = albumTDao.findOne(query,AlbumT.class);
        if (albumT!=null){
            AlbumTVo albumTVo = new AlbumTVo();
            BeanUtils.copyProperties(albumT, albumTVo);
            //分类名称
            if (albumT.getMenuCategoryId()!=null){
                albumTVo.setCategoryName(menuCategoryTService.findById(albumT.getMenuCategoryId()).getCategoryName());
            }
            albumTVo.setCreateTime(BaseTools.longToString3(albumT.getCreateTime()));
            albumTVo.setUpdateTime(BaseTools.longToString(albumT.getUpdateTime()));
            return albumTVo;
        }else {
            solrService.remove(id);
            throw new WhyException(ResultEnum.OBJISNULL);
        }
    }

    /**
     * 查询所有专辑
     * @return
     */
    @Override
    public List<AlbumT> findAll() {
        //查询未删除和未禁用的所有专辑
        Query query = new Query();
        query.addCriteria(Criteria.where("removed").is(false).and("enable").is(true));
        List<AlbumT> list = albumTDao.findAll(query,AlbumT.class);
        return list;
    }

    /**
     * 分页查询专辑
     * @param albumTDTO
     * @return
     */
    @Override
    public Page findByPage(AlbumTDTO albumTDTO) {
        //查询未删除的专辑，并分页传给视图
        Query query = new Query();
        query.addCriteria(Criteria.where("removed").is(false));
        query.with(new Sort(Sort.Direction.DESC, "updateTime"));
        if (StringUtils.isNoneEmpty(albumTDTO.getMenuCategoryId())){
            query.addCriteria(Criteria.where("menuCategoryId").is(albumTDTO.getMenuCategoryId()));
        }else {
            List<MenuCategoryT> menuCategoryTList = menuCategoryTService.findMenuCategoryListByMenuId(albumTDTO.getMenuId());
            if (menuCategoryTList!=null){
                /*String[] menuCategoryIds = new String[menuCategoryTList.size()];
                for (int i=0;i<menuCategoryTList.size();i++){
                    menuCategoryIds[i]=menuCategoryTList.get(i).getId();
                }
                query.addCriteria(Criteria.where("menuCategoryId").in(menuCategoryIds));*/
                ArrayList<String> menuCategoryIds = new ArrayList<>();
                for (MenuCategoryT menuCategoryT:menuCategoryTList){
                    menuCategoryIds.add(menuCategoryT.getId());
                }
                query.addCriteria(Criteria.where("menuCategoryId").in(menuCategoryIds));
            }
        }
        if (StringUtils.isNoneEmpty(albumTDTO.getContentCategoryId())){
            query.addCriteria(Criteria.where("contentCategoryId").is(albumTDTO.getContentCategoryId()));
        }
        //辅助分类查询
        if (StringUtils.isNoneEmpty(albumTDTO.getAuxiliaryCategoryId())){
            query.addCriteria(Criteria.where("auxiliaryCategoryId").is(albumTDTO.getAuxiliaryCategoryId()));
        }
        if(StringUtils.isNotEmpty(albumTDTO.getAlbumName())){
            query.addCriteria(Criteria.where("albumName").regex(albumTDTO.getAlbumName()));
        }
        //省和市
        if (StringUtils.isNoneEmpty(albumTDTO.getProvinceId())){
            query.addCriteria(Criteria.where("provinceId").is(albumTDTO.getProvinceId()));
        }
        if (StringUtils.isNoneEmpty(albumTDTO.getCityId())){
            query.addCriteria(Criteria.where("cityId").is(albumTDTO.getCityId()));
        }
        long count = albumTDao.count(query, AlbumT.class);
        List<AlbumTVo> list = new ArrayList<>();
        for (AlbumT albumT : albumTDao.findByPage(query, albumTDTO, AlbumT.class)) {
            AlbumTVo vo = new AlbumTVo();
            BeanUtils.copyProperties(albumT, vo);
            //分类名称
            if (albumT.getMenuCategoryId()!=null){
                vo.setCategoryName(menuCategoryTService.findById(albumT.getMenuCategoryId()).getCategoryName());
                //分类全称
                List<MenuCategoryT> fathers= menuCategoryTService.findFathers(albumT.getMenuCategoryId());
                String categoryAllName = "";
                if (fathers!=null){
                    for (MenuCategoryT menuCategory : fathers){
                        categoryAllName += menuCategory.getCategoryName() + "-";
                    }
                }
                vo.setCategoryAllName(categoryAllName.substring(0,categoryAllName.length()-1));
            }
            //辅助分类
            if (albumT.getAuxiliaryCategoryId()!=null){
                vo.setAuxiliaryCategoryId(albumT.getAuxiliaryCategoryId());
                AuxiliaryCategoryT auxiliaryCategoryT = auxiliaryCategoryTService.findById(albumT.getAuxiliaryCategoryId());
                if (auxiliaryCategoryT!=null){
                    vo.setAuxiliaryCategoryFatherName(auxiliaryCategoryTService.findById(auxiliaryCategoryT.getPid()).getCategoryName());
                    vo.setAuxiliaryCategoryName(auxiliaryCategoryT.getCategoryName());
                }
            }
            //内容类型跳转地址
            if (albumT.getContentCategoryId()!=null){
                ContentCategoryT contentCategoryT = contentCategoryTService.findCategoryById(albumT.getContentCategoryId());
                if (contentCategoryT!=null){
                    vo.setDetailUrl(contentCategoryTService.findById(albumT.getContentCategoryId()).getUrl());
                }
            }
            vo.setCreateTime(BaseTools.longToString3(albumT.getCreateTime()));
            vo.setUpdateTime(BaseTools.longToString(albumT.getUpdateTime()));
            list.add(vo);
        }
        return new Page(albumTDTO, count, list);
    }

    /**
     * 增加浏览次数
     */
    @Override
    public void setViewCount(String id) {
        AlbumT albumT = findById(id);
        albumT.setViewsNum(albumT.getViewsNum()+1);
        albumTDao.saveOrupdate(albumT);
    }

    /**
     * 查询菜单分类下的所有专辑列表
     * @param menuCategoryId
     * @return
     */
    @Override
    public List<AlbumT> findByMenuCategory(String menuCategoryId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("removed").is(false).and("menuCategoryId").is(menuCategoryId));
        query.with(new Sort(Sort.Direction.DESC, "updateTime"));
        List<AlbumT> list = albumTDao.findAll(query,AlbumT.class);
        return list;
    }

    /**
     * 查询首页数据
     * @param programaId
     * @param count 每个模块展示多少条
     * @return
     */
    @Override
    public Map<String, List<AlbumTVo>> homeData(String programaId,int count) {
        List<MenuT> menuTList = menuTService.findMenuListByProgramaId(programaId);
        Map<String,List<AlbumTVo>> resultMap = new HashMap<>();
        if (menuTList!=null&&menuTList.size()>0){
            for (int i=0;i<menuTList.size();i++){
                List<MenuCategoryT> menuCategoryTList = menuCategoryTService.findMenuCategoryListByMenuId(menuTList.get(i).getId());
                List<AlbumTVo> resultList = new ArrayList<>();
                if (menuCategoryTList!=null&&menuCategoryTList.size()>0){
                    for (int j=0;j<menuCategoryTList.size();j++){
                        List<AlbumT> albumTList = findByMenuCategory(menuCategoryTList.get(j).getId());
                        if (albumTList!=null&&albumTList.size()>0){
                            for (int k=0;k<albumTList.size();k++){
                                AlbumTVo vo = new AlbumTVo();
                                if (k<count){
                                    BeanUtils.copyProperties(albumTList.get(k), vo);
                                    //菜单索引
                                    vo.setIndex(i+1);
                                    //详细地址
                                    ContentCategoryT contentCategoryT = contentCategoryTService.findById(albumTList.get(k).getContentCategoryId());
                                    vo.setDetailUrl(contentCategoryT.getUrl());
                                    //内容
                                    /*List<ContentTVo> contentTVos = contentTService.findByAlbum(albumTList.get(0).getId(),albumTList.get(0).getContentCategoryId());
                                    if (contentTVos!=null&&contentTVos.size()>0){
                                        vo.setDetailUrl(contentTVos.get(0).getUrl());
                                        *//*if (vo.getAlbumIntro() == null) {
                                            String content = contentTVos.get(0).getContent();
                                            String resultContent = content.split("</p>")[0]+"</p>";
                                            vo.setAlbumIntro(resultContent);
                                        }*//*
                                    }*/
                                    resultList.add(vo);
                                }
                            }
                        }
                    }
                }
                resultMap.put(menuTList.get(i).getMenuName(),resultList);
            }
        }
        return resultMap;
    }

    @Override
    public List<AlbumT> findByProgramaId(String proogramaId){
        List<AlbumT> resultList = new ArrayList<>();
        //查询该站点下的所有菜单
        List<MenuT> menuList = menuTService.findMenuListByProgramaId(proogramaId);
        if (menuList.size()>0){
            for (MenuT menuT:menuList){
                //查询该菜单下的专辑分类
                List<MenuCategoryT> categoryList = menuCategoryTService.findMenuCategoryListByMenuId(menuT.getId());
                if (categoryList.size()>0){
                    for (MenuCategoryT menuCategoryT : categoryList){
                        //查询该专辑分类下的专辑
                        List<AlbumT> albumList = findByMenuCategory(menuCategoryT.getId());
                        if (albumList.size()>0){
                            for (AlbumT albumT:albumList){
                                resultList.add(albumT);
                            }
                        }
                    }
                }
            }
        }
        return resultList;
    }

}
